import { t } from 'i18next'
import { DcsEntity } from '@/api/manager/dcs/interface'
import { useTableAllStore } from './blocks/main/table/all/store'
import {
	getItemByMeetingMoid,
	getItemByMtKey,
	getItemInTree,
	getParentByChildMeetingMoid,
	getParentByChildMtKey,
	getWeightExceptVip,
	meetingListSort,
	mtListSort,
} from './blocks/main/table/all/utils'
import { useTableInteractiveStore } from './blocks/main/table/interactive/store'
import { useTableOftenStore } from './blocks/main/table/often/store'
import { useTableDcsStore } from './blocks/main/table/dcs/store'
import { useManagerStore } from './blocks/main/manager/store'
import { useParamsStore } from './blocks/main/store'
import { transDcsModel } from '@/api/manager/dcs/translator'
import { isMatch } from './utils/utils'
import { dcsListSort } from './blocks/main/table/dcs/utils'
import { useMccStore } from './store'
import { MccModel, transMccModel } from './blocks/main/table/all/translator'
import { Meeting, MeetingEntity, revert_meeting } from '@/api/manager/meeting'
import { useVipStore } from './blocks/vip/store'
import { Mt, MtEntity, revert_mt } from '@/api/manager/mt'
import { orgTreeRx, useOrgTreeStore } from './blocks/main/organizeTree/store'
import { useTableOrgStore } from './blocks/main/table/organize/store'
import { IOrgTreeUpdateMt } from './blocks/main/organizeTree/translator'
import { isExistMtEntity, transEntityMtToMeeting } from './utils/translator'
import { oftenMtSort } from './blocks/main/table/often/utils'
import { transOften } from '@/api/manager/often/translator'
import { mtListInteractiveSort } from './blocks/main/table/interactive/utils'
import { transInteractive } from '@/api/manager/interactive/translator'
import { transOrg } from '@/api/manager/organize/translator'
import { getItemInOrgTree, getOrgItemById } from './blocks/main/organizeTree/utils'
import { orgMtSort } from './blocks/main/table/organize/utils'
import { IMccMeetingSimpleInfo } from './blocks/main/manager/translator'
import { useGlobalStore } from '@/store/global'
import Alert from '@/components/Alert'
import { fetchGetPlatformServiceUrl } from '@/api/global'
import { useSmsStore } from './blocks/sms/store'
import { useSelectStore } from './blocks/select/store'
import { useMixStore } from './blocks/mix/store'
import { usePollStore } from './blocks/poll/store'
import { useChasingStore } from './blocks/chasing/store'
import { useMccMtInfoStore } from './blocks/mccMtInfo/store'
import { useRollCallStore } from './blocks/roll/store'
/**
 * 发言方管理方变动
 */
export const mcc_meeting_simpleInfo = (data: IMccMeetingSimpleInfo) => {
	simpleInfoTableAll(data)
	const isSuperMeeting = useMccStore.getState().mccInfo.superMtNum
	if (isSuperMeeting) {
		simpleInfoTableInteractive(data)
	} else {
		simpleInfoTableOften(data)
	}
	simpleInfoTableOrg(data)
	simpleInfoTableDcs(data)
	//更新管理方发言方
	const tree = useTableAllStore.getState().tree
	let nextSpeaker = null
	if (isExistMtEntity(data.speaker)) {
		data.speaker.speaker = 1
		if (data.speaker.mt_type !== 7 && data.speaker.mt_type !== 8) {
			let _mt = new Mt(data.speaker)
			let meetingInTree = getItemByMtKey(tree, data.speaker.mt_key) as MccModel<Mt> | null
			if (meetingInTree) {
				_mt.status.isDoubleFlow = meetingInTree.mcc.status.isDoubleFlow
				_mt.status.isMute = meetingInTree.mcc.status.isMute
			}
			nextSpeaker = _mt
		} else {
			let meetingInTree = getItemByMtKey(tree, data.speaker.mt_key) as MccModel<Meeting> | null
			let meeting = transEntityMtToMeeting(data.speaker, meetingInTree?.mcc.parentId ?? '')
			nextSpeaker = new Meeting(meeting)
		}
	}
	useManagerStore.setState({
		speaker: nextSpeaker,
		isChairmanSelectView: data.chairman_selectview === 1,
	})
	const isMeetingAdminOrCreator = useMccStore.getState().isMeetingAdminOrCreator
	if (!isMeetingAdminOrCreator) {
		const moid = useGlobalStore.getState().user?.moid
		if (moid !== data.chairman.moid) {
			Alert(t('您的管理员权限已被取消'), function () {
				fetchGetPlatformServiceUrl()
					.then((data) => {
						window.location.href = data + '/index.html'
					})
					.catch((err) => {
						window.location.href = '/meeting/index.html'
					})
			})
		}
	}
	let nextChairman = null
	if (isExistMtEntity(data.chairman)) {
		data.chairman.chairman = 1
		let _mt = new Mt(data.chairman)
		let meetingInTree = getItemByMtKey(tree, data.chairman.mt_key) as MccModel<Mt> | null
		if (meetingInTree) {
			_mt.status.isMute = meetingInTree.mcc.status.isMute
		}
		nextChairman = _mt
	}
	useManagerStore.setState({
		chairman: nextChairman,
	})
}
function simpleInfoTableAll({ speaker, chairman, force_brd: forceBrd }: IMccMeetingSimpleInfo) {
	let tree = useTableAllStore.getState().tree
	const prevSpeaker = useManagerStore.getState().speaker
	const prevChairman = useManagerStore.getState().chairman
	const sortType = useParamsStore.getState().tableSort
	const vipList = useVipStore.getState().list
	//有新发言方
	if (isExistMtEntity(speaker)) {
		//有旧发言方
		if (prevSpeaker) {
			//两者不一致
			if (speaker.mt_key !== prevSpeaker.mtKey) {
				let nextItem = getItemByMtKey(tree, speaker.mt_key)
				if (nextItem) {
					nextItem.mcc.status.isSpeaker = true
					if (nextItem.mcc.isMt) {
						if (isExistMtEntity(forceBrd)) {
							nextItem.mcc.status.isForceBrd = true
						} else {
							nextItem.mcc.status.isForceBrd = false
						}
					}
					nextItem.attr.weightExceptVipInSortType2 = getWeightExceptVip(nextItem.mcc)
					//排序，本级和下级才排
					if (nextItem.mcc.confLevel !== 1) {
						let parent = getParentByChildMtKey(tree, nextItem.mtKey)
						if (parent) {
							let mtList = parent.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
							let meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
							const vipMtKeyList = vipList.map((x) => x.mtKey)
							const resultMtList = mtListSort(mtList, sortType, vipMtKeyList)
							const resultMeetingList = meetingListSort(meetingList, sortType)
							parent.children = [...resultMtList, ...resultMeetingList]
						}
					}
				}
				let prevItem = getItemByMtKey(tree, prevSpeaker.mtKey)
				if (prevItem) {
					prevItem.mcc.status.isSpeaker = false
					if (prevItem.mcc.isMt) {
						prevItem.mcc.status.isForceBrd = false
					}
					prevItem.attr.weightExceptVipInSortType2 = getWeightExceptVip(prevItem.mcc)
					//排序
					if (prevItem.mcc.confLevel !== 1) {
						let parent = getParentByChildMtKey(tree, prevItem.mtKey)
						if (parent) {
							let mtList = parent.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
							let meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
							const vipMtKeyList = vipList.map((x) => x.mtKey)
							const resultMtList = mtListSort(mtList, sortType, vipMtKeyList)
							const resultMeetingList = meetingListSort(meetingList, sortType)
							parent.children = [...resultMtList, ...resultMeetingList]
						}
					}
				}
			}
		} else {
			let nextItem = getItemByMtKey(tree, speaker.mt_key)
			if (nextItem) {
				nextItem.mcc.status.isSpeaker = true
				if (nextItem.mcc.isMt) {
					if (isExistMtEntity(forceBrd)) {
						nextItem.mcc.status.isForceBrd = true
					} else {
						nextItem.mcc.status.isForceBrd = false
					}
				}
				nextItem.attr.weightExceptVipInSortType2 = getWeightExceptVip(nextItem.mcc)
				//排序
				if (nextItem.mcc.confLevel !== 1) {
					let parent = getParentByChildMtKey(tree, nextItem.mtKey)
					if (parent) {
						let mtList = parent.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
						let meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
						const vipMtKeyList = vipList.map((x) => x.mtKey)
						const resultMtList = mtListSort(mtList, sortType, vipMtKeyList)
						const resultMeetingList = meetingListSort(meetingList, sortType)
						parent.children = [...resultMtList, ...resultMeetingList]
					}
				}
			}
		}
	} else {
		if (prevSpeaker) {
			let prevItem = getItemByMtKey(tree, prevSpeaker.mtKey)
			if (prevItem) {
				prevItem.mcc.status.isSpeaker = false
				if (prevItem.mcc.isMt) {
					prevItem.mcc.status.isForceBrd = false
				}
				prevItem.attr.weightExceptVipInSortType2 = getWeightExceptVip(prevItem.mcc)
				//排序
				if (prevItem.mcc.confLevel !== 1) {
					let parent = getParentByChildMtKey(tree, prevItem.mtKey)
					if (parent) {
						let mtList = parent.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
						let meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
						const vipMtKeyList = vipList.map((x) => x.mtKey)
						const resultMtList = mtListSort(mtList, sortType, vipMtKeyList)
						const resultMeetingList = meetingListSort(meetingList, sortType)
						parent.children = [...resultMtList, ...resultMeetingList]
					}
				}
			}
		}
	}
	if (isExistMtEntity(chairman)) {
		if (prevChairman) {
			if (chairman.mt_key !== prevChairman.mtKey) {
				let nextItem = getItemByMtKey(tree, chairman.mt_key) as MccModel<Mt>
				if (nextItem) {
					nextItem.mcc.status.isChairman = true
					nextItem.attr.weightExceptVipInSortType2 = getWeightExceptVip(nextItem.mcc)
					//排序
					if (nextItem.mcc.confLevel !== 1) {
						let parent = getParentByChildMtKey(tree, nextItem.mtKey)
						if (parent) {
							let mtList = parent.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
							let meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
							const vipMtKeyList = vipList.map((x) => x.mtKey)
							const resultMtList = mtListSort(mtList, sortType, vipMtKeyList)
							const resultMeetingList = meetingListSort(meetingList, sortType)
							parent.children = [...resultMtList, ...resultMeetingList]
						}
					}
				}
				let prevItem = getItemByMtKey(tree, prevChairman.mtKey) as MccModel<Mt>
				if (prevItem) {
					prevItem.mcc.status.isChairman = false
					prevItem.attr.weightExceptVipInSortType2 = getWeightExceptVip(prevItem.mcc)
					//排序
					if (prevItem.mcc.confLevel !== 1) {
						let parent = getParentByChildMtKey(tree, prevItem.mtKey)
						if (parent) {
							let mtList = parent.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
							let meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
							const vipMtKeyList = vipList.map((x) => x.mtKey)
							const resultMtList = mtListSort(mtList, sortType, vipMtKeyList)
							const resultMeetingList = meetingListSort(meetingList, sortType)
							parent.children = [...resultMtList, ...resultMeetingList]
						}
					}
				}
			}
		} else {
			let nextItem = getItemByMtKey(tree, chairman.mt_key) as MccModel<Mt>
			if (nextItem) {
				nextItem.mcc.status.isChairman = true
				nextItem.attr.weightExceptVipInSortType2 = getWeightExceptVip(nextItem.mcc)
				//排序
				if (nextItem.mcc.confLevel !== 1) {
					let parent = getParentByChildMtKey(tree, nextItem.mtKey)
					if (parent) {
						let mtList = parent.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
						let meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
						const vipMtKeyList = vipList.map((x) => x.mtKey)
						const resultMtList = mtListSort(mtList, sortType, vipMtKeyList)
						const resultMeetingList = meetingListSort(meetingList, sortType)
						parent.children = [...resultMtList, ...resultMeetingList]
					}
				}
			}
		}
	} else {
		if (prevChairman) {
			let prevItem = getItemByMtKey(tree, prevChairman.mtKey) as MccModel<Mt>
			if (prevItem) {
				prevItem.mcc.status.isChairman = false
				prevItem.attr.weightExceptVipInSortType2 = getWeightExceptVip(prevItem.mcc)
				//排序
				if (prevItem.mcc.confLevel !== 1) {
					let parent = getParentByChildMtKey(tree, prevItem.mtKey)
					if (parent) {
						let mtList = parent.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
						let meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
						const vipMtKeyList = vipList.map((x) => x.mtKey)
						const resultMtList = mtListSort(mtList, sortType, vipMtKeyList)
						const resultMeetingList = meetingListSort(meetingList, sortType)
						parent.children = [...resultMtList, ...resultMeetingList]
					}
				}
			}
		}
	}
	useTableAllStore.setState({
		tree: { ...tree },
	})
}
function simpleInfoTableOften({ speaker, chairman, force_brd: forceBrd }: IMccMeetingSimpleInfo) {
	const list = useTableOftenStore.getState().list
	const prevSpeaker = useManagerStore.getState().speaker
	const prevChairman = useManagerStore.getState().chairman
	if (isExistMtEntity(speaker)) {
		if (prevSpeaker) {
			if (speaker.mt_key !== prevSpeaker.mtKey) {
				for (const item of list) {
					if (item.mtKey === speaker.mt_key) {
						item.mcc.status.isSpeaker = true
						if (isExistMtEntity(forceBrd)) {
							item.mcc.status.isForceBrd = true
						} else {
							item.mcc.status.isForceBrd = false
						}
					}
					if (item.mtKey === prevSpeaker.mtKey) {
						item.mcc.status.isSpeaker = false
						item.mcc.status.isForceBrd = false
					}
				}
			}
		} else {
			for (const item of list) {
				if (item.mtKey === speaker.mt_key) {
					item.mcc.status.isSpeaker = true
					if (isExistMtEntity(forceBrd)) {
						item.mcc.status.isForceBrd = true
					} else {
						item.mcc.status.isForceBrd = false
					}
				}
			}
		}
	} else {
		if (prevSpeaker) {
			for (const item of list) {
				if (item.mtKey === prevSpeaker.mtKey) {
					item.mcc.status.isSpeaker = false
					item.mcc.status.isForceBrd = false
				}
			}
		}
	}
	if (isExistMtEntity(chairman)) {
		if (prevChairman) {
			for (const item of list) {
				if (item.mtKey === chairman.mt_key) {
					item.mcc.status.isChairman = true
				}
				if (item.mtKey === prevChairman.mtKey) {
					item.mcc.status.isChairman = false
				}
			}
		} else {
			for (const item of list) {
				if (item.mtKey === chairman.mt_key) {
					item.mcc.status.isChairman = true
				}
			}
		}
	} else {
		if (prevChairman) {
			for (const item of list) {
				if (item.mtKey === prevChairman.mtKey) {
					item.mcc.status.isChairman = false
				}
			}
		}
	}
	useTableOftenStore.setState({
		list: [...list],
	})
}
function simpleInfoTableInteractive({ speaker, chairman, force_brd: forceBrd }: IMccMeetingSimpleInfo) {
	const list = useTableInteractiveStore.getState().list
	const sortType = useParamsStore.getState().tableSort
	const prevSpeaker = useManagerStore.getState().speaker
	const prevChairman = useManagerStore.getState().chairman
	const vipList = useVipStore.getState().list
	if (isExistMtEntity(speaker)) {
		if (prevSpeaker) {
			if (speaker.mt_key !== prevSpeaker.mtKey) {
				for (const item of list) {
					if (item.mtKey === speaker.mt_key) {
						item.mcc.status.isSpeaker = true
						if (isExistMtEntity(forceBrd)) {
							item.mcc.status.isForceBrd = true
						} else {
							item.mcc.status.isForceBrd = false
						}
						item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
					}
					if (item.mtKey === prevSpeaker.mtKey) {
						item.mcc.status.isSpeaker = false
						item.mcc.status.isForceBrd = false
						item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
					}
				}
			}
		} else {
			for (const item of list) {
				if (item.mtKey === speaker.mt_key) {
					item.mcc.status.isSpeaker = true
					if (isExistMtEntity(forceBrd)) {
						item.mcc.status.isForceBrd = true
					} else {
						item.mcc.status.isForceBrd = false
					}
					item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
				}
			}
		}
	} else {
		if (prevSpeaker) {
			for (const item of list) {
				if (item.mtKey === prevSpeaker.mtKey) {
					item.mcc.status.isSpeaker = false
					item.mcc.status.isForceBrd = false
					item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
				}
			}
		}
	}
	if (isExistMtEntity(chairman)) {
		if (prevChairman) {
			for (const item of list) {
				if (item.mtKey === chairman.mt_key) {
					item.mcc.status.isChairman = true
					item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
				}
				if (item.mtKey === prevChairman.mtKey) {
					item.mcc.status.isChairman = false
					item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
				}
			}
		} else {
			for (const item of list) {
				if (item.mtKey === chairman.mt_key) {
					item.mcc.status.isChairman = true
					item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
				}
			}
		}
	} else {
		if (prevChairman) {
			for (const item of list) {
				if (item.mtKey === prevChairman.mtKey) {
					item.mcc.status.isChairman = false
					item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
				}
			}
		}
	}
	const vipMtKeyList = vipList.map((x) => x.mtKey)
	let result = mtListInteractiveSort(list, sortType, vipMtKeyList)
	useTableInteractiveStore.setState({
		list: [...result],
	})
}
function simpleInfoTableOrg({ speaker, chairman, force_brd: forceBrd }: IMccMeetingSimpleInfo) {
	const list = useTableOrgStore.getState().list
	const prevSpeaker = useManagerStore.getState().speaker
	const prevChairman = useManagerStore.getState().chairman
	if (isExistMtEntity(speaker)) {
		if (prevSpeaker) {
			if (speaker.mt_key !== prevSpeaker.mtKey) {
				for (const item of list) {
					if (item.mtKey === speaker.mt_key) {
						item.mcc.status.isSpeaker = true
						if (isExistMtEntity(forceBrd)) {
							item.mcc.status.isForceBrd = true
						} else {
							item.mcc.status.isForceBrd = false
						}
					}
					if (item.mtKey === prevSpeaker.mtKey) {
						item.mcc.status.isSpeaker = false
						item.mcc.status.isForceBrd = false
					}
				}
			}
		} else {
			for (const item of list) {
				if (item.mtKey === speaker.mt_key) {
					item.mcc.status.isSpeaker = true
					if (isExistMtEntity(forceBrd)) {
						item.mcc.status.isForceBrd = true
					} else {
						item.mcc.status.isForceBrd = false
					}
				}
			}
		}
	} else {
		if (prevSpeaker) {
			for (const item of list) {
				if (item.mtKey === prevSpeaker.mtKey) {
					item.mcc.status.isSpeaker = false
					item.mcc.status.isForceBrd = false
				}
			}
		}
	}
	if (isExistMtEntity(chairman)) {
		if (prevChairman) {
			for (const item of list) {
				if (item.mtKey === chairman.mt_key) {
					item.mcc.status.isChairman = true
				}
				if (item.mtKey === prevChairman.mtKey) {
					item.mcc.status.isChairman = false
				}
			}
		} else {
			for (const item of list) {
				if (item.mtKey === chairman.mt_key) {
					item.mcc.status.isChairman = true
				}
			}
		}
	} else {
		if (prevChairman) {
			for (const item of list) {
				if (item.mtKey === prevChairman.mtKey) {
					item.mcc.status.isChairman = false
				}
			}
		}
	}
	useTableOrgStore.setState({
		list: [...list],
	})
}
function simpleInfoTableDcs({ speaker, chairman, force_brd: forceBrd }: IMccMeetingSimpleInfo) {
	const list = useTableDcsStore.getState().list
	const prevSpeaker = useManagerStore.getState().speaker
	const prevChairman = useManagerStore.getState().chairman
	if (isExistMtEntity(speaker)) {
		if (prevSpeaker) {
			if (speaker.mt_key !== prevSpeaker.mtKey) {
				for (const item of list) {
					if (item.mtKey === speaker.mt_key) {
						item.mcc.status.isSpeaker = true
						if (isExistMtEntity(forceBrd)) {
							item.mcc.status.isForceBrd = true
						} else {
							item.mcc.status.isForceBrd = false
						}
					}
					if (item.mtKey === prevSpeaker.mtKey) {
						item.mcc.status.isSpeaker = false
						item.mcc.status.isForceBrd = false
					}
				}
			}
		} else {
			for (const item of list) {
				if (item.mtKey === speaker.mt_key) {
					item.mcc.status.isSpeaker = true
					if (isExistMtEntity(forceBrd)) {
						item.mcc.status.isForceBrd = true
					} else {
						item.mcc.status.isForceBrd = false
					}
				}
			}
		}
	} else {
		if (prevSpeaker) {
			for (const item of list) {
				if (item.mtKey === prevSpeaker.mtKey) {
					item.mcc.status.isSpeaker = false
					item.mcc.status.isForceBrd = false
				}
			}
		}
	}
	if (isExistMtEntity(chairman)) {
		if (prevChairman) {
			for (const item of list) {
				if (item.mtKey === chairman.mt_key) {
					item.mcc.status.isChairman = true
				}
				if (item.mtKey === prevChairman.mtKey) {
					item.mcc.status.isChairman = false
				}
			}
		} else {
			for (const item of list) {
				if (item.mtKey === chairman.mt_key) {
					item.mcc.status.isChairman = true
				}
			}
		}
	} else {
		if (prevChairman) {
			for (const item of list) {
				if (item.mtKey === prevChairman.mtKey) {
					item.mcc.status.isChairman = false
				}
			}
		}
	}
	useTableDcsStore.setState({
		list: [...list],
	})
}
/**
 * 新增、更新
 */
export const mcc_mt = (mts: MtEntity[]) => {
	mtChangeTableAll({ mts, cascade: { mt_key: '0.0.0.0_0', id: '0_2' } })
	const isSuperMeeting = useMccStore.getState().mccInfo.superMtNum
	if (isSuperMeeting) {
		mtChangeTableInteractive(mts)
	} else {
		mtChangeTableOften(mts)
	}
	const sortType = useParamsStore.getState().tableSort
	if (sortType === 3) {
		mtChangeTableOrg(mts)
	}
	//改变speaker和chairman的双流状态，顺便其他状态都一起改了
	mccChangeChairman(mts)
	mccChangeSpeaker(mts)
	//todo 可以根据curPage选择更新
	useVipStore.getState().ws.mcc_mt(mts)
	useSmsStore.getState().updateList(mts)
	useMixStore.getState().updateMuteForMix(mts)
	usePollStore.getState().updateList(mts)
	useChasingStore.getState().updateList(mts)
	//todo 点名轮询更新， 终端信息更新
	useRollCallStore.getState().mccUpdateList(mts)
}
/**
 * 新增、更新下级
 */
export const mcc_sub_smcu_mt = ({ mts, cascade }: { mts: MtEntity[]; cascade: MeetingEntity }) => {
	mtChangeTableAll({ mts, cascade })
	const isSuperMeeting = useMccStore.getState().mccInfo.superMtNum
	if (isSuperMeeting) {
	} else {
		mtChangeTableOften(mts)
	}
	const sortType = useParamsStore.getState().tableSort
	if (sortType === 3) {
		mtChangeTableOrg(mts)
	}
	//改变speaker和chairman的双流状态，顺便其他状态都一起改了
	mccChangeSpeaker(mts)
	//todo 可以根据curPage选择更新
	useSmsStore.getState().updateList(mts)
	useMixStore.getState().updateMuteForMix(mts)
	usePollStore.getState().updateList(mts)
	useChasingStore.getState().updateList(mts)
	//todo 点名轮询更新， 终端信息更新
	useRollCallStore.getState().mccUpdateList(mts)
}
/**
 * 新增、更新观众
 */
export const mcc_audience = (mts: MtEntity[]) => {
	mtChangeTableAll({ mts, cascade: { mt_key: '0.0.0.0_0', id: '0_2' } })
	const isSuperMeeting = useMccStore.getState().mccInfo.superMtNum
	const sortType = useParamsStore.getState().tableSort
	if (sortType === 3 && !!isSuperMeeting) {
		mtChangeTableOrg(mts)
	}
}
function mtChangeTableAll({ mts, cascade: smcu }: { mts: MtEntity[]; cascade: { mt_key: string; id: string } }) {
	const tree = useTableAllStore.getState().tree
	const keywords = useParamsStore.getState().keywords
	const sortType = useParamsStore.getState().tableSort
	const vipList = useVipStore.getState().list
	let currentMeeting = getItemByMtKey(tree, smcu.mt_key)
	let __AddMts__: MtEntity[] = []
	let __updateMts__: IOrgTreeUpdateMt[] = []
	if (currentMeeting && currentMeeting.mcc.status.isOnline) {
		let newMtList = currentMeeting.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
		let meetingList = currentMeeting.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
		//mt存在重复情况，以后面的为准
		for (const mt of mts) {
			//mcc_mt 会有上级会议节点信息
			if (mt.mt_type === 8) {
				if (tree.mtKey === mt.mt_key) {
					tree.mcc.status.isOnline = !!mt.online
					tree.mcc.status.isSilence = !!mt.silence
					tree.mcc.status.isMute = !!mt.mute
					tree.mcc.status.isDoubleFlow = !!mt.doubleflow
					tree.mcc.status.isUpMt = !!mt.up_mt
					tree.mcc.status.isSpeaker = !!mt.speaker
					tree.mcc.name = mt.name
				}
			} else {
				let count = 0 //记录是否新增
				for (const item of [...newMtList, ...meetingList]) {
					if (item.mtKey === mt.mt_key) {
						count = 1
						if (mt.mt_type === 7) {
							item.mcc.status.isOnline = !!mt.online
							item.mcc.status.isSilence = !!mt.silence
							item.mcc.status.isMute = !!mt.mute
							item.mcc.status.isDoubleFlow = !!mt.doubleflow
							item.mcc.status.isUpMt = !!mt.up_mt
							item.mcc.status.isSpeaker = !!mt.speaker
							item.status.isChecked = false
							if (item.mcc.isMt) {
								item.mcc.INITIAL_NAME = mt.name
							} else {
								item.mcc.name = mt.name
							}
						} else {
							__updateMts__ = [
								...__updateMts__,
								{
									mtKey: item.mtKey,
									prevIsOnline: item.mcc.status.isOnline,
									nowIsOnline: !!mt.online,
								},
							]
							item.mcc = new Mt(mt)
						}
						item.status.isCalling = false
						item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
					}
				}
				//新增
				if (count === 0) {
					if (mt.mt_type === 7) {
						let meeting = transEntityMtToMeeting(mt, smcu.id)
						let model = transMccModel(new Meeting(meeting))
						meetingList = [...meetingList, model]
					} else {
						__AddMts__ = [...__AddMts__, mt]
						let model = transMccModel(new Mt(mt))
						newMtList = [...newMtList, model]
					}
				}
			}
			const resultMeetingList = meetingListSort(meetingList, sortType).map((x) => {
				if (!x.mcc.status.isOnline) {
					x.status.isMatchSearch = isMatch(x.mcc, keywords)
				}
				return x
			})
			const vipMtKeyList = vipList.map((x) => x.mtKey)
			const resultMtList = mtListSort(newMtList, sortType, vipMtKeyList).map((x) => {
				x.status.isMatchSearch = isMatch(x.mcc, keywords)
				return x
			})
			currentMeeting.children = [...resultMtList, ...resultMeetingList]
		}
	}
	useTableAllStore.setState({ tree: { ...tree } })
	cometd_mcc_mt({
		addMts: __AddMts__,
		updateMts: __updateMts__,
		mts,
	})
}
export const cometd_mcc_mt = ({
	addMts,
	updateMts,
	mts,
}: {
	addMts: MtEntity[]
	updateMts: IOrgTreeUpdateMt[]
	mts: MtEntity[]
}) => {
	let mtOnline: MtEntity[] = [] //下线到上线的终端
	let mtOffline: MtEntity[] = [] //上线到下线的终端
	let newAddMts: MtEntity[] = [] //新加的终端
	for (const updateMt of updateMts) {
		if (updateMt.prevIsOnline === updateMt.nowIsOnline) {
			continue
		}
		let mt = mts.find((x) => x.mt_key === updateMt.mtKey)
		if (mt) {
			if (updateMt.prevIsOnline) {
				mtOffline.push(mt)
			} else {
				mtOnline.push(mt)
			}
		}
	}
	for (const addMt of addMts) {
		newAddMts.push(addMt)
		if (addMt.online === 1) {
			//新增的且上线的终端
			mtOnline.push(addMt)
		}
	}
	useRollCallStore.getState().mtOnlineStatusChangeNotify(mtOnline, mtOffline, newAddMts, false)
}
function mtChangeTableOften(mts: MtEntity[]) {
	const list = useTableOftenStore.getState().list
	const keywords = useParamsStore.getState().keywords
	const vipList = useVipStore.getState().list
	let newMtList = [...list]
	for (const mt of mts) {
		let item = newMtList.find((x) => x.mtKey === mt.mt_key)
		if (item) {
			if (!!mt.often_mt) {
				item.mcc = new Mt(mt)
				item.status.isCalling = false
			} else {
				//移除了常用终端
				newMtList = newMtList.filter((x) => x.mtKey !== mt.mt_key)
			}
		} else {
			if (!!mt.often_mt) {
				let model = transOften(mt)
				model.status.isMatchSearch = isMatch(model.mcc, keywords)
				newMtList.push(model)
			}
		}
	}
	const vipMtKeyList = vipList.map((x) => x.mtKey)
	let result = oftenMtSort(newMtList, vipMtKeyList)
	useTableOftenStore.setState({ list: result })
}
function mtChangeTableInteractive(mts: MtEntity[]) {
	const list = useTableInteractiveStore.getState().list
	const keywords = useParamsStore.getState().keywords
	const sortType = useParamsStore.getState().tableSort
	const vipList = useVipStore.getState().list
	let newMtList = [...list]
	for (const mt of mts) {
		let count = 0
		for (const item of newMtList) {
			if (item.mtKey === mt.mt_key) {
				count = 1
				item.mcc = new Mt(mt)
				item.status.isCalling = false
				item.attr.weightExceptVipInSortType2 = getWeightExceptVip(item.mcc)
			}
		}
		//新增
		if (count === 0) {
			let model = transInteractive(mt)
			model.status.isMatchSearch = isMatch(model.mcc, keywords)
			newMtList.push(model)
		}
	}
	const vipMtKeyList = vipList.map((x) => x.mtKey)
	let result = mtListInteractiveSort(newMtList, sortType, vipMtKeyList)
	useTableInteractiveStore.setState({
		list: result,
	})
}
function mtChangeTableOrg(mts: MtEntity[]) {
	const organizeTree = useOrgTreeStore.getState().tree
	const list = useTableOrgStore.getState().list
	const keywords = useParamsStore.getState().keywords
	const currentOrgId = useParamsStore.getState().currentOrgId
	let newMtList = [...list]
	let __AddMts__: MtEntity[] = []
	let __updateMts__: IOrgTreeUpdateMt[] = []
	for (const mt of mts) {
		let count = 0
		for (const item of list) {
			if (item.mtKey === mt.mt_key) {
				count = 1
				__updateMts__ = [
					...__updateMts__,
					{
						mtKey: item.mtKey,
						prevIsOnline: item.mcc.status.isOnline,
						nowIsOnline: !!mt.online,
					},
				]
				item.mcc = new Mt(mt)
				item.status.isCalling = false
			}
		}
		//新增
		if (count === 0) {
			let model = transOrg(mt)
			model.status.isMatchSearch = isMatch(model.mcc, keywords)
			let orgItem = getOrgItemById(organizeTree, currentOrgId)
			if (
				orgItem &&
				orgItem.id !== 'often' &&
				orgItem.id !== 'interactive' &&
				orgItem.id !== 'dcs' &&
				orgItem.id !== 'live'
			) {
				let mtKeys: string[] = []
				getItemInOrgTree([orgItem], (item) => {
					mtKeys = [...mtKeys, ...item.org.users.map((x) => x.mtKey)]
				})
				if (mtKeys.includes(model.mtKey)) {
					model.status.isMatchOrgTree = true
				} else {
					model.status.isMatchOrgTree = false
				}
			}
			newMtList.push(model)
			__AddMts__ = [...__AddMts__, mt]
		}
	}
	newMtList = orgMtSort(newMtList)
	useTableOrgStore.setState({
		list: newMtList,
	})
	if (__AddMts__.length > 0) {
		orgTreeRx.addMt$.next()
	} else {
		useOrgTreeStore.getState().updateMts(__updateMts__)
	}
}
function mccChangeChairman(mts: MtEntity[]) {
	let chairmanList = mts.filter((x) => !!x.chairman)
	if (chairmanList.length > 0) {
		const chairman = useManagerStore.getState().chairman
		let chairmanList = mts.filter((x) => !!x.chairman)
		let latest = chairmanList[chairmanList.length - 1]
		latest.chairman = 1
		if (chairman && chairman.mtKey === latest.mt_key) {
			chairman.status.isMute = !!latest.mute
		}
		let _mt = null
		if (chairman) {
			_mt = new Mt(revert_mt(chairman))
		}
		useManagerStore.setState({
			chairman: _mt,
		})
	}
}
function mccChangeSpeaker(mts: MtEntity[]) {
	let speakerList = mts.filter((x) => !!x.speaker)
	if (speakerList.length > 0) {
		const speaker = useManagerStore.getState().speaker
		let speakerList = mts.filter((x) => !!x.speaker)
		let latest = speakerList[speakerList.length - 1]
		latest.speaker = 1
		if (speaker && speaker.mtKey === latest.mt_key) {
			speaker.status.isDoubleFlow = !!latest.doubleflow
			speaker.status.isMute = !!latest.mute
		}
		let _mt = null
		if (speaker) {
			if (speaker.mtType !== 7 && speaker.mtType !== 8) {
				_mt = new Mt(revert_mt(speaker as Mt))
			} else {
				_mt = new Meeting(revert_meeting(speaker as Meeting))
			}
		}
		useManagerStore.setState({
			speaker: _mt,
		})
	}
}
/**
 * 删除观众
 */
export const mcc_audience_del = (mtKey: string) => {
	useTableAllStore.getState().delMts([mtKey])
	const sortType = useParamsStore.getState().tableSort
	if (sortType === 3) {
		useTableOrgStore.getState().delMts([mtKey])
	}
	//判断终端或者会议删除时  是否展开终端信息
	const curPage = useMccStore.getState().curPage
	const mtInfoMt = useMccMtInfoStore.getState().mt
	if (curPage === 'mt_info' && mtInfoMt?.mtKey === mtKey) {
		useMccStore.getState().setCurPage('mcc_main')
	}
}
/**
 * 删除下级终端
 */
export const mcc_sub_smcu_mt_del = (mtKeys: string[]) => {
	useTableAllStore.getState().delMts(mtKeys)
	const isSuperMeeting = useMccStore.getState().mccInfo.superMtNum
	if (isSuperMeeting) {
		useTableInteractiveStore.getState().delMts(mtKeys)
	} else {
		useTableOftenStore.getState().delMts(mtKeys)
	}
	const sortType = useParamsStore.getState().tableSort
	if (sortType === 3) {
		useTableOrgStore.getState().delMts(mtKeys)
	}
	useTableDcsStore.getState().delMts(mtKeys)
	const curPage = useMccStore.getState().curPage
	//todo 可以根据curPage选择更新
	useSelectStore.getState().removeLi(mtKeys)
	useSmsStore.getState().removeMt(mtKeys)
	useMixStore.getState().removeLi(mtKeys)
	usePollStore.getState().removeMt(mtKeys)
	useChasingStore.getState().removeMt(mtKeys)
	// window.TS.mcc.rollCall.removeLi({ mtKey: mtKey })
	// window.TS.mcc.rollCall.mtOnlineStatusChangeNotify([], [{ mtKey: mtKey }], [], true)
	useRollCallStore.getState().removeLi(mtKeys)
	useRollCallStore.getState().mtOnlineStatusChangeNotify(
		[],
		mtKeys.map((x) => ({ mt_key: x })),
		[],
		true
	)
	//判断终端或者会议删除时  是否展开终端信息
	const mtInfoMt = useMccMtInfoStore.getState().mt
	if (curPage === 'mt_info' && mtKeys.includes(mtInfoMt?.mtKey)) {
		useMccStore.getState().setCurPage('mcc_main')
		//todo 是否需要手动终止轮询，应该是不需要的，mtinfo里自己做了
	}
}
/**
 * 删除终端
 */
export const mcc_mt_del = (mtKey: string) => {
	useTableAllStore.getState().delMts([mtKey])
	const isSuperMeeting = useMccStore.getState().mccInfo.superMtNum
	if (isSuperMeeting) {
		useTableInteractiveStore.getState().delMts([mtKey])
	} else {
		useTableOftenStore.getState().delMts([mtKey])
	}
	const sortType = useParamsStore.getState().tableSort
	if (sortType === 3) {
		useTableOrgStore.getState().delMts([mtKey])
	}
	useTableDcsStore.getState().delMts([mtKey])
	useVipStore.getState().removeMt(mtKey)
	const curPage = useMccStore.getState().curPage
	//todo 可以根据curPage选择更新
	useSelectStore.getState().removeLi([mtKey])
	useSmsStore.getState().removeMt([mtKey])
	useMixStore.getState().removeLi([mtKey])
	usePollStore.getState().removeMt([mtKey])
	useChasingStore.getState().removeMt([mtKey])
	// window.TS.mcc.rollCall.removeLi({ mtKey: mtKey })
	// window.TS.mcc.rollCall.mtOnlineStatusChangeNotify([], [{ mtKey: mtKey }], [], true)
	useRollCallStore.getState().removeLi([mtKey])
	useRollCallStore.getState().mtOnlineStatusChangeNotify([], [{ mt_key: mtKey } as MtEntity], [], true)
	//判断终端或者会议删除时  是否展开终端信息
	const mtInfoMt = useMccMtInfoStore.getState().mt
	if (curPage === 'mt_info' && mtInfoMt?.mtKey === mtKey) {
		useMccStore.getState().setCurPage('mcc_main')
		//todo 是否需要手动终止轮询，应该是不需要的，mtinfo里自己做了
	}
}
/**
 * 删除下级级联节点
 */
export const mcc_smcu_remove = (id: string) => {
	const tree = useTableAllStore.getState().tree
	let parent = getParentByChildMeetingMoid(tree, id)
	if (parent) {
		parent.children = parent.children.filter((x) => x.mcc.isMt || x.mcc.id !== id)
	}
	useTableAllStore.setState({
		tree: { ...tree },
	})
	orgTreeRx.reload$.next()
	//判断终端或者会议删除时  是否展开终端信息
	const curPage = useMccStore.getState().curPage
	const mtInfoMt = useMccMtInfoStore.getState().mt
	if (curPage === 'mt_info' && mtInfoMt?.mtKey === id) {
		useMccStore.getState().setCurPage('mcc_main')
	}
}
/**
 * 增加/更新级联节点
 * 更新的情况：上级更新会推，下级会议更新走 mcc_mt，不会走这个
 */
export const mcc_smcu_add = (addMeeting: MeetingEntity) => {
	let tree = useTableAllStore.getState().tree
	const keywords = useParamsStore.getState().keywords
	const sortType = useParamsStore.getState().tableSort
	const vipList = useVipStore.getState().list
	let flag = false
	//上级会议
	if (addMeeting.conf_level === 1) {
		if (tree.mtKey === addMeeting.mt_key) {
			if (tree.mcc.status.isOnline !== !!addMeeting.online) {
				flag = true
			}
			tree.mcc.status.isOnline = !!addMeeting.online
			tree.mcc.status.isSilence = !!addMeeting.silence
			tree.mcc.status.isMute = !!addMeeting.mute
			tree.mcc.status.isDoubleFlow = !!addMeeting.doubleflow
			tree.mcc.status.isUpMt = !!addMeeting.up_mt
			tree.mcc.status.isSpeaker = !!addMeeting.speaker

			tree.mcc.name = addMeeting.name
		} else {
			flag = true
			//新增 构造上级会议级联
			let model = transMccModel(new Meeting(addMeeting))
			model.status.isOpen = true
			tree.mcc.parentId = '0_1'
			model.children = [tree]
			tree = model
		}
	} else {
		let parent = getItemByMeetingMoid(tree, addMeeting.parent_id)
		if (parent) {
			flag = true
			let prevMeeting = getItemByMtKey(tree, addMeeting.mt_key)
			if (prevMeeting) {
				prevMeeting.mcc = new Meeting(addMeeting)
				prevMeeting.status.isChecked = false
				prevMeeting.status.isCalling = false
				prevMeeting.status.isMatchSearch = true
				prevMeeting.attr.weightExceptVipInSortType2 = getWeightExceptVip(prevMeeting.mcc)
			} else {
				let model = transMccModel(new Meeting(addMeeting))
				parent.children = [...parent.children, model]
			}
			let newMtList = parent.children.filter((x) => x.mcc.isMt) as MccModel<Mt>[]
			let meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
			const resultMeetingList = meetingListSort(meetingList, sortType).map((x) => {
				if (!x.mcc.status.isOnline) {
					x.status.isMatchSearch = isMatch(x.mcc, keywords)
				}
				return x
			})
			const vipMtKeyList = vipList.map((x) => x.mtKey)
			const resultMtList = mtListSort(newMtList, sortType, vipMtKeyList).map((x) => {
				x.status.isMatchSearch = isMatch(x.mcc, keywords)
				return x
			})
			parent.children = [...resultMtList, ...resultMeetingList]
		}
	}
	useTableAllStore.setState({
		tree: { ...tree },
	})
	//细化，从无到有，从在线到离线，从离线到在线，才需要重新调用组织架构树接口和获取组织架构列表接口
	if (flag) {
		orgTreeRx.reload$.next()
	}
}
/**
 * 会议信息变动
 */
export const mcc_conf_detail = (data: { subject: string }) => {
	const preSubject = useMccStore.getState().mccInfo.subject
	if (preSubject !== data.subject) {
		useMccStore.setState((v) => ({ ...v, mccInfo: { ...v.mccInfo, subject: data.subject } }))
		let tree = useTableAllStore.getState().tree
		let currentMeeting = getItemByMtKey(tree, '0.0.0.0_0') as MccModel<Meeting>
		if (currentMeeting) {
			currentMeeting.mcc.name = data.subject
		}
		useTableAllStore.setState({
			tree: { ...tree },
		})
	}
}
/**
 * dcs终端
 */
export const mcc_dcs_mt = (mts: DcsEntity[]) => {
	let list = useTableDcsStore.getState().list
	const chairman = useManagerStore.getState().chairman
	const speaker = useManagerStore.getState().speaker
	const keywords = useParamsStore.getState().keywords
	for (const item of mts) {
		let mt = transDcsModel(item)
		mt.status.isMatchSearch = isMatch(mt.mcc, keywords)
		list = list.filter((x) => x.mtKey !== mt.mtKey)
		list.push(mt)
	}
	list = dcsListSort(list.filter((x) => x.mcc.status.isOnline || x.dcs.isDcs))
	for (const item of list) {
		if (chairman && chairman.mtKey === item.mtKey) {
			item.mcc.status.isChairman = true
		} else {
			item.mcc.status.isChairman = false
		}
		if (speaker && speaker.mtKey === item.mtKey) {
			item.mcc.status.isSpeaker = true
		} else {
			item.mcc.status.isSpeaker = false
		}
	}
	useTableDcsStore.setState({
		list: [...list],
	})
}
/**
 * dcs状态
 */
export const mcc_dcs_conf_status = (dcsMode: 0 | 1 | 2) => {
	useTableDcsStore.getState().ws.mcc_dcs_conf_status(dcsMode)
	//dcs 关闭
	if (dcsMode === 0) {
		const tree = useTableAllStore.getState().tree
		const oftenList = useTableOftenStore.getState().list
		const interactiveList = useTableInteractiveStore.getState().list
		getItemInTree(tree, (item) => {
			if (item.mcc.isMt) {
				item.mcc.status.isDcs = false
			}
		})
		for (const item of oftenList) {
			item.mcc.status.isDcs = false
		}
		for (const item of interactiveList) {
			item.mcc.status.isDcs = false
		}
		useTableAllStore.setState({
			tree: { ...tree },
		})
		useTableOftenStore.setState({
			list: [...oftenList],
		})
		useTableInteractiveStore.setState({
			list: [...interactiveList],
		})
	}
}
